<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Home\Controller;

use Home\Common\Weixinpay\Wxtk;
use Think\Controller;

/**
 * 林州市悟能科技提供技术支持
 * 400-037203
 * @author Mr_Lee :672288511;
 */
class OrderController extends Controller
{
    public function _initialize()
    {
        if (empty($_SESSION['username'])) {


            $this->error('页面加载中。。。', U('Login/Login'), 1);

        }
        $table1="order";
        $this->assign('table',$table1);
    }

    public function Orderadmin()
    {

        if (IS_POST || IS_GET) {
           if (I('wtime')) {
               $wtime = strtotime(I('wtime'));
           } else {
               $wtime = 0;
           }

           

           if (I('gntime')) {
               $ntime = strtotime(I('ntime'));
           } else {
               $ntime = time();
           }

            if (I('kehuname')) {
                $mae['name'] = array('like', '%' . I('kehuname') . '');
                $kh = M('wxuser')->where($mae)->select();
                foreach ($kh as $k => $v) {
                    $khname = $v['openid'] . ',';
                }

                $khname2 = rtrim($khname, ",");

            } else {
                $khname2 = '';
            }



            // echo $sijidianhua;
            if (I('is_px')) {
                if (I('is_px') == 1) {
                    $sor = 'addtime desc';
                } else {
                    $sor = 'starttime desc';
                }
            } else {
                $sor = 'addtime desc';
            }



            if (!empty(I('wtime2')) && !empty(I('ntime2'))) {
                $wtime2 = I('wtime2');
                $ntime2 = I('ntime2');
                $wheretime['starttime'] = array('between', '' . $wtime2 . ',' . $ntime2 . '');
            } else {
                $wtime2 = '';
                $ntime2 = date('Y-m-d H:i:s');
            }



            if (!empty(I('wtime')) && !empty(I('ntime'))) {
                $wtime = strtotime(I('wtime'));
                $ntime = strtotime(I('ntime'));
                $wheretime['addtime'] = array('between', '' . $wtime . ',' . $ntime . '');
            } else {
                $wtime = 0;
                $ntime = time();
            }
            if ($wheretime == '') {
                $wheretime['addtime'] = array('between', '' . $wtime . ',' . $ntime . '');
            }
            if (!empty(I('is_pay'))) {
                $wheretime['pay_statu'] = I('is_pay');
            }
            $this->assign('wtime', I('wtime'));
            $this->assign('ntime', I('ntime'));
            $wherex = array(
                'starttime' => array('between', '' . date('Y-m-d H:i:s', $wtime) . ',' . date('Y-m-d H:i:s', $ntime) . ''),
                'addtime' => array('between', '' . $wtime . ',' . $ntime . ''),
                '_logic' => 'or',
            );


            // echo $wtime;
            // echo '-';
            // echo $ntime;die;


            if ($khname2) {


                $where1 = array(
                    '_complex' => $wheretime,


                    // 'siji' => array('like', '%' . I('sj')),   cbing 2018年05月19日20:09:05
                    'openid' => $khname2,
                );
            } else {

                $where1 = array(
                    '_complex' => $wheretime,
                    // 'dianhua' => array('like', '%' . I('dianhua')),

                    // 'siji' => array('like', '%' . I('sj')),   cbing 2018年05月19日20:09:12
                );
            }


        } else {
            $where1 = array(
                'addtime' => array('like', '%'), 
            );
            $sor = 'id desc';
        }


            $sijixingming = urldecode(I('xingming'));
            $sijidianhua = I('dianhua');
            // echo $sijidianhua;
            // if(I('xingming')){
            //     $sijixingming = I('xingming');
            // }
            // if(I('dianhua')){
            //     $sijidianhua = I('dianhua');
            // }
            if($sijixingming){
                $where1 = array(
                    '_complex' => $wheretime,
                    'xingming' => array('like', '%'.$sijixingming.'%'), 
                );
            }

            if($sijidianhua){
                $where1 = array(
                    '_complex' => $wheretime,
                    'dianhua' => array('like', '%'.$sijidianhua.'%'), 
                );
            }

           
            // $where['pay_status_sk'] = I('pay_status_sk');
            // $where1 = array(
            //     '_complex' => $wheretime,
            //     'pay_status_sk' => array('eq',I('pay_status_sk')), 
            // );
             

        //全部订单
        // $where = array(

        //     '_complex' => $where1, // 复合查询

        // );

        $where = $where1;

        //未支付订单
        $where2 = array(
            'pay_statu' => 0,
            '_complex' => $where1, // 复合查询

        );
        //已支付订单
        $where3 = array(
            'pay_statu' => 1,
            '_complex' => $where1, // 复合查询
        );
        //已完成订单
        $where4 = array(
            'order_statu' => 6,
            '_complex' => $where1, // 复合查询

        );
        //未完成订单
        $where5 = array(
            'order_statu' => array('neq', 6),
            '_complex' => $where1, // 复合查询

        );
        $where6 = array(
            'pay_statu' => 1,
            'is_ypay' => 1,
            '_complex' => $where1, // 复合查询

        );
        
        $where['status']=I('statu');

        if($where['status']=='5')
        {
            $where['status']=array('elt',5);
        }elseif($where['status'] == 6){
            $where['status'] = array('eq',6);
        }elseif($where['status'] == 7){
            $where['status'] = array('eq',7);
        }else{
            unset($where['status']);
        }

        $pay_status_sk = I('pay_status_sk');

        if($pay_status_sk ==2){
            $where['pay_status_sk'] = 0;
            $where['status'] = 6;
        }elseif($pay_status_sk ==1){
            $where['pay_status_sk'] = $pay_status_sk;
        }



        if(I('order_cwstatus'))
        {
            unset($where['pay_statu']);
            // unset($where['_complex']);
            unset($where['dianhua']);
            $where['order_cwstatus']=I('order_cwstatus');
            $this->assign('order_cwstatus',I('order_cwstatus'));
        }
        
        if(I('open_status'))
        {
            $where['openid'] ='';
        }
        
        

        $order = M('xllog');

        $count = $order->where($where)->count();

        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数(25)

        $show = $Page->show();// 分页显示输出

        $olist = $order->where($where)->limit($Page->firstRow . ',' . $Page->listRows)->order($sor)->select();
// dump($olist);die;
        
        // foreach ($olist as $k => $v) {

        //     $olist[$k]['chufa_time']=D('price')->where('id='.$v['pathid'])->getfield('fc_time');
        // }
        // dump($olist);die;
        // dump($olist);die;
        //var_dump($order->_sql());

        $ylist = $order->where($where)->select();
        $plist = $order->getLastSql();
        $this->assign('plist', $plist);
        $bycount = $order->where($where3)->count('id');//已支付笔数
        $bwcount = $order->where($where2)->count('id');//未支付笔数
        $bycount2 = $order->where($where3)->sum('price');//已支付金额
        $bwcount2 = $order->where($where2)->sum('price');//未支付金额
        $yycount = $order->where($where6)->sum('price');//余额支付金额
        $sj = M('siji')->select();
        $this->assign('sj', $sj);
        //$this->assign('bywcount', $bywcount);
        //$this->assign('bwwcount', $bwwcount);
        $data_all   = I();
        $this->assign(array(
                'kehuname'      => $data_all['kehuname'],
                'wtime'         => $data_all['wtime'],
                'ntime'         => $data_all['ntime'],
                'wtime2'        => $data_all['wtime2'],
                'ntime2'        => $data_all['ntime2'],
                'statu'         => $data_all['statu'],
                'xingming'      => $data_all['xingming'],
                'dianhua'       => $data_all['dianhua'],
                'is_px'         => $data_all['is_px'],
                'pay_status_sk' => $data_all['pay_status_sk'],
                'datas'         => $data_all
        ));


        $this->assign('bycount2', $bycount2);
        $this->assign('bwcount2', $bwcount2);
        $this->assign('bwcount', $bwcount);
        $this->assign('bcount2', $bwcount2 + $bycount2);
        $this->assign('bycount', $bycount);
        $this->assign('bcount', $bycount + $bwcount);

        $this->assign('yycount', $yycount);

        //  var_dump($olist);
        $this->assign('page', $show);

        

        foreach ($olist as $k => $v) {
            if(empty($v['siji'])){
                $olist[$k]['siji'] = get_sijiname($v['openid']);
            }
        }
        $this->assign('olist', $olist);
        $this->display();


    }

    public function baodan()
    {
        if (IS_AJAX) {
           $id=I('orderid');
            $res=D('xllog')->where('id='.$id)->getfield('openid');
            if($res)
            {
                $order_cwstatus['order_cwstatus']='1';
                $res1=D('xllog')->where('id='.$id)->save($order_cwstatus);
                if($res1)
                {
                    echo 1;die;
                }else{
                    echo 2;die;
                }
            }
           
        }
    }
    public function orderprint()
    {
        if (IS_AJAX) {
            $order = M('xllog');

            $list = $order->query(stripslashes(I('post.sql')));

            // $this->show(stripslashes(I('post.sql')));
            $this->assign('list', $list);
            $this->display();

        }
    }

    public function bcshow()
    {
        $map['id'] = I('post.bcbh');
        $order = M('xllog')->where($map)->find();
        

        $payinfo = M('paylog')->where(array('orderid' => $order['orderid']))->find();
        // dump($order);
        // dump($payinfo);
        $mab['openid'] = $order['openid'];
        $xm = M('siji')->where($mab)->find();

        $order['price']=$order['price']*$order['num'];


        //平台手续费
        $tixianfeilv = D('user')->field('tixianfeilv,offline,offline1,offline2,offline3')->find(1);


        if($order['pay_status_sk']==0)
        {      
            $shouxubili = ($tixianfeilv['tixianfeilv']+$tixianfeilv['offline1']+$tixianfeilv['offline2']+$tixianfeilv['offline3'])/100;
            
        }else
        {
            $shouxubili = ($tixianfeilv['offline']+$tixianfeilv['offline1']+$tixianfeilv['offline2']+$tixianfeilv['offline3'])/100;
        }
        $order['tixianfeilv']  = $order['price']*($shouxubili);
        $order['practical']    = $order['price']-($order['price']*($shouxubili));

        $order['saveinfo']      = json_decode($order['saveinfo'],true);

        $this->assign('payinfo', $payinfo);
        $this->assign('xm', $xm);
        $this->assign('order', $order);

        $this->display();
    }
    /**
     * [sub_order_info2 description]
     * @return [type] [description]
     */
    public function sub_order_info2()
    {
        $data=I('post.');

        if(!empty($data['openid']))
        {   
            $where      = 'openid="'.$data['openid'].'"';
            $result     = D('siji')->field('openid,xingming,dianhua,status')->where($where)->find();
            empty($result) && $this->error('找不到该司机或还未审核通过');
            $result['status']!=1 && $this->error('该司机还未审核通过');
            $data['openid']     = $result['openid'];
            $data['xingming']   = $result['xingming'];
            $data['dianhua']    = $result['dianhua'];

            $data['status']    = 0;
        }

        $res=D('xllog')->save($data);
        $this->success('修改成功');
    }
    /**
     * 修改订单,并发送短信和邮件提醒司机订单状态已经修改
     * @return [type] [description]
     */
    public function sub_order_info()
    {
        $data=I('post.');
        $user_data=D('wxuser')->field('tel')->where('openid="'.$data['openid'].'"')->find();
        if(!empty($user_data['tel']))
        {
            $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
            );
            $smsapi = "http://api.smsbao.com/";
            $user = "cbing"; //短信平台帐号
            $pass = md5("xyz98765"); //短信平台密码

            $content="派单信息，请及时查看【小易出行】";//要发送的短信内容
            // $phone = $user_data['tel'];//要发送短信的手机号码
            $phone ="15527344177";
            $sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
            $result =file_get_contents($sendurl);

        }

        if(empty($user_data['email']))
        {
            $email="2487937004@qq.com";
            $res=think_send_mail($email,'小易出行','小易出行','派单信息，请及时查看【小易出行】');
          
        }
//        $openidtel = explode('-',$data['openidtel']);
//        $data['openid'] = $openidtel[0];
//        $data['dianhua'] = $openidtel[1];
//        unset($data['openidtel']);
        $res=D('xllog')->save($data);
        $this->success('修改成功');
    }

  public function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null){

            $config = C('THINK_EMAIL');
           
            vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件

            vendor('SMTP');

            $mail = new PHPMailer(); //PHPMailer对象

            $mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码

            $mail->IsSMTP(); // 设定使用SMTP服务

            $mail->SMTPDebug = 0; // 关闭SMTP调试功能

            // 1 = errors and messages

            // 2 = messages only

            $mail->SMTPAuth = true; // 启用 SMTP 验证功能

            $mail->SMTPSecure = 'ssl'; // 使用安全协议

            $mail->Host = $config['SMTP_HOST']; // SMTP 服务器

            $mail->Port = $config['SMTP_PORT']; // SMTP服务器的端口号

            $mail->Username = $config['SMTP_USER']; // SMTP服务器用户名

            $mail->Password = $config['SMTP_PASS']; // SMTP服务器密码

            $mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);

            $replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];

            $replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];

            $mail->AddReplyTo($replyEmail, $replyName);

            $mail->Subject = $subject;

            $mail->AltBody = "为了查看该邮件，请切换到支持 HTML 的邮件客户端"; 

            $mail->MsgHTML($body);

            $mail->AddAddress($to, $name);

            if(is_array($attachment)){ // 添加附件

                foreach ($attachment as $file){

                    is_file($file) && $mail->AddAttachment($file);

                }

            }

            return $mail->Send() ? true : $mail->ErrorInfo;

    }

     public function bcshow_table()
    {
        $map['id'] = I('post.bcbh');
        $order = M('xllog')->where($map)->find();
        $siji = $order['siji'];
        if(empty($siji)){
            $siji = get_sijiname($order['openid']);
        }
        $payinfo = M('paylog')->where(array('orderid' => $order['orderid']))->find();
        $mab['openid'] = $order['openid'];
        $xm = M('wxuser')->where($mab)->find();
        $order['price']=$order['price']*$order['num'];
        $sj = M('siji')->select();
        $this->assign('sj', $sj);
        $this->assign('siji', $siji);

        $this->assign('payinfo', $payinfo);
        $this->assign('xm', $xm);
        $this->assign('order', $order);

        $this->display();
    }

    public function kcshow()
    {


        $this->assign('zb', I('post.kcname'));
        //echo I('post.kcname');
        if (I('post.fs') == '1') {

            $this->assign('fs', '出发地');

        } else {
            $this->assign('fs', '目的地');
        }
        $this->display();
    }

    public function del()
    {

        $map['id'] = I('get.id');
        $del = M('xllog')->where($map)->delete();
        if ($del) {

            $this->success('删除成功');
        } else {

            $this->error('删除失败');
        }

    }

    public function dd()
    {
        $map['id'] = I('get.id');
        $data['order_statu'] = 2;
        $del = M('xllog')->where($map)->save($data);
        if ($del) {

            $this->success('设置成功');
        } else {

            $this->error('设置失败');
        }


    }

    public function tztemplate($orderid, $id, $zt)
    {
        import('Common.Wechat.Wechat');
        $map['id'] = $id;
        $config = M('User')->where($map)->find();
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $config['appid'], // 填写高级调用功能的app id
            'appsecret' => $config['appsecret'], // 填写高级调用功能的密钥
            'partnerid' => $config['partnerid'], // 财付通商户身份标识
            'partnerkey' => $config['partnerkey'], // 财付通商户权限密钥Key
            //'paysignkey' => $config ["paysignkey"]  // 商户签名密钥Key
        );
        $weObj = new \Common\Wechat\Wechat ($options);
        $access_token = $weObj->sendTemplateMessage2();
        $mas['orderid'] = $orderid;

        $openid = M('xllog')->where($mas)->getfield('openid');
        if ($zt == 1) {
            $template = array(
                'touser' => $openid,
                'template_id' => $config['tztemplate'],

                'url' => "http://" . $_SERVER ['SERVER_NAME'] . "/index.php?s=/Index/pay/id/1/orderid/" . $orderid . ".html",
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => array('value' => urlencode("尊敬的用户您好："), 'color' => "#743A3A"),
                    'OrderSn' => array('value' => urlencode($orderid), 'color' => '#000'),
                    'OrderStatus' => array('value' => urlencode("您的订单客服已确认,请您尽快支付"), 'color' => '#000'),

                    'remark' => array('value' => "点击此信息即可付款", 'color' => '#000'),
                )
            );
        } else if ($zt == 2) {

            $template = array(
                'touser' => $openid,
                'template_id' => $config['tztemplate'],
                'url' => "http://" . $_SERVER ['SERVER_NAME'] . "/index.php?s=/Index/index/id/1.html",
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => array('value' => urlencode("尊敬的用户您好："), 'color' => "#743A3A"),
                    'OrderSn' => array('value' => urlencode($orderid), 'color' => '#000'),
                    'OrderStatus' => array('value' => urlencode("您的订单客服已取消"), 'color' => '#000'),


                    'remark' => array('value' => "取消原因:对不起,暂无车辆请选择其他行程时间"),
                )
            );

        } else if ($zt == 3) {
            $template = array(
                'touser' => $openid,
                'template_id' => $config['tztemplate'],
                'url' => "http://" . $_SERVER ['SERVER_NAME'] . "/index.php?s=/Index/ddstatu/orderid/" . $orderid . ".html",
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => array('value' => urlencode("尊敬的用户您好："), 'color' => "#743A3A"),
                    'OrderSn' => array('value' => urlencode($orderid), 'color' => '#000'),
                    'OrderStatus' => array('value' => urlencode("您的订单已支付成功"), 'color' => '#000'),


                    'remark' => array('value' => "点击可查看订单详情"),
                )
            );
        } else if ($zt == 4) {
            $template = array(
                'touser' => $openid,
                'template_id' => $config['tztemplate'],
                'url' => "http://" . $_SERVER ['SERVER_NAME'] . "/index.php?s=/Index/ddstatu/orderid/" . $orderid . ".html",
                'topcolor' => "#7B68EE",
                'data' => array(
                    'first' => array('value' => urlencode("尊敬的用户您好："), 'color' => "#743A3A"),
                    'OrderSn' => array('value' => urlencode($orderid), 'color' => '#000'),
                    'OrderStatus' => array('value' => urlencode("您的订单已完成，感谢您的使用"), 'color' => '#000'),


                    'remark' => array('value' => ""),
                )
            );
        }
        $json_template = json_encode($template);
//echo $json_template;
//echo $this->access_token;
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $this->http_request($url, urldecode($json_template));


    }

    public function http_request($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我们在POST数据哦！
        curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    public function tuikuan()
    {
        if (IS_AJAX) {
            if (session('tk_qx') == 1) {
        $map['id'] = 1;
        $config = M('User')->where($map)->find();
        $payinfo = M('paylog')->where(array('id' => I('post.id')))->find();
        import('Common.Weixinpay.Wxtk');
        $Wxtk = new Wxtk();
        $Wxtk->setParameter("appid", $config['appid']);
        $Wxtk->setParameter("mch_id", $config['partnerid']);
        $Wxtk->setParameter("nonce_str", $this->generateNonceStr());
        $Wxtk->setParameter("transaction_id", $payinfo['orderno']);
        $Wxtk->setParameter("out_trade_no", $payinfo['orderid']);
        $Wxtk->setParameter("out_refund_no", $payinfo['orderid'] . "tk");
        $Wxtk->setParameter("total_fee", $payinfo['price'] * 100);
        $Wxtk->setParameter("refund_fee", I('post.price') * 100);
        $ss = $Wxtk->create_tuikuan_xml($config['partnerkey']);
        $responseXml = $Wxtk->curl_post_ssl('https://api.mch.weixin.qq.com/secapi/pay/refund', $ss);
        $responseObj = simplexml_load_string($responseXml, 'SimpleXMLElement', LIBXML_NOCDATA);

        if ($responseObj->return_code == 'SUCCESS') {

            $maps['id'] = I('post.id');
            $datas['pay_statu'] = 999;
            $datas['tk_orderid'] = $payinfo['orderid'] . "tk";
            M('paylog')->where($maps)->save($datas);

            M('xllog')->where(array('orderid' => $payinfo['orderid']))->save($datas);
            M('paylog')->where($maps)->setInc('tk_price', $responseObj->refund_fee / 100);
            M('xllog')->where(array('orderid' => $payinfo['orderid']))->setInc('tk_price', $responseObj->refund_fee / 100);
            $datass = "退款处理成功";
        } else {
            $datass = "操作失败：" . $responseObj->return_msg ;
        }
            }else{
                $datass="对不起您没有退款权限";
            }
            $this->ajaxReturn($datass);}

    }

    private function generateNonceStr($length = 16)
    {
        // 密码字符集，可任意添加你需要的字符
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $str;
    }


    /**
     * 提现列表
     */
    public function withdraw(){
        $count = M('withdraw')->count();
        $Page = new \Think\Page($count, 20);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        $withdraw = M('withdraw')->limit($Page->firstRow . ',' . $Page->listRows)->select();
   		
        $this->assign('page', $show);
        $this->assign('res', 1);
        $this->assign('withdraw',$withdraw);
        $this->display();
    }

    /**
     * 提现审核
     */
    public function checkflag(){
        if(IS_AJAX){
            $id = I("post.id");
            $status = I("post.check");
            $log     = D('withdraw')->where('id='.$id)->find();
            $yue     = D('wxuser')->where('uid='.$log['uid'])->getfield('yue');
            if($status==2)
            {
                if($yue<$log['money'])
                {
                    datamsg(0,'用户余额不足');
                }
            }
            
            $result = M('withdraw')->where(array('id'=>$id))->save(array('status'=>$status));

            if($result){
                
                if($status==2)
                {
                    
                    $openid  = D('wxuser')->where('uid='.$log['uid'])->getfield('openid');
                    
                    $status_wx = M('wxuser')->where(array('uid'=>$log['uid']))->setDec('yue',$log['money']);

                    $data   = array(
                        'user_id'       => $log['uid'],
                        'create_time'   => time(),
                        'desc'          => '用户提现，打款成功：'.$log['money'],
                        'price'         => $log['money'],
                        'tx_status'     => 2,
                        'card'          => $log['card'],
                    );
                    $status_wx2 =D('money_log')->add($data);

                    //把所有订单全部修改状态
                    $endToday=getWeek();   
                    $total=D('xllog')->field('id,orderid')->where('openid="'.$openid.'" and status=6 and addtime<='.$endToday.' and withdraw_status=0')->select();
                    if(!empty($total))
                    {
                        foreach ($total as $k => $v) {
                            M('xllog')->where(array('id'=>$v['id']))->save(array('withdraw_status'=>1));
                        }
                    }
                }else
                {
                    D('withdraw_log')->where('withdraw_id='.$log['id'])->delete();
                }   
               
                
                datamsg(1,'审核成功');
            }else{
            
                datamsg(0,'审核失败');
            }
        }
        $id = I('get.id');
        $withdraw = M('withdraw')->where(array('id'=>$id))->find();
        $this->assign('withdraw',$withdraw);
        $this->assign('id',$id);
        $this->display();
    }

    /**
     * 所有订单
     * @return [type] [description]
     */
    public function allOrder()
    {

        $id  =  I('id');

        $res = D('withdraw_log')->where('withdraw_id='.$id)->find();


        if(!empty($res))
        {
            if (I('post.wtime')) {
                $wtime = strtotime(I('post.wtime'));
            } else {
                $wtime = 0;
            }
            if (I('post.ntime')) {
                $ntime = strtotime(I('post.ntime'));
            } else {

                $ntime = time();
            }

            $this->assign('wtime', I('post.wtime'));
            $this->assign('ntime', I('post.ntime'));

            $where1 = array(
                'addtime' => array('between', '' . $wtime . ',' . $ntime . ''),
            );

            $order = json_decode($res['order'],1);
            $where1['id']    = array('in', $order);
            $list  = D('xllog')->where($where1)->select();

            $where2 = array(
            '_complex' => $where1, // 复合查询
            );
            $where3 = array(
                'status' => 6,
                '_complex' => $where1, // 复合查询
            );
            $where4 = array(
                'status' => 6,
                '_complex' => $where1, // 复合查询
            );
            $order = M('xllog');
            $bwcount = $order->where($where2)->count('id');
            $bwcount2 = $order->where($where2)->sum('price*num');
            $bwcount3 = $order->where($where3)->count('id');
            $bwcount4 = $order->where($where4)->sum('price*num');

            $this->assign(array(
                    'bwcount'   => $bwcount,
                    'bwcount2'  => $bwcount2,
                    'bwcount3'  => $bwcount3,
                    'bwcount4'  => $bwcount4,
                    'id'        => $id
            ));
        }else
        {
            $this->success('暂无更多数据');die;
        }
        foreach ($list as $key => $value) {
            if($value['pay_statu']==1)
            {
                if($value['pay_status_sk'] ==1)
                {
                    $list[$key]['pay_statu']='现金支付';
                }else
                {
                    $list[$key]['pay_statu']='线上支付';
                }
            }else
            {
                $list[$key]['pay_statu']='未支付';
            }
        }
        

        $this->assign('list',$list);
        $this->display('allorder');
    }

    public function excel()
    {   
        $datas  = I();
        $datas['xingming']  = urldecode($datas['xingming']);
        $datas['kehuname']  = urldecode($datas['kehuname']);
    
        $where  = $this->wheres($datas);
      
        
        $status = array(
            '创建订单','到达固定乘车点','接到乘客','接到乘客','到达终点站','确认订单','订单完成','撤销订单'
            );
        $list = M('xllog')->field('openid,mobile,num,start,end,pay_statu,addtime,status,pathid,pay_status_sk,starttime,price,total_price')->where($where)->order('id desc')->select();
       
        foreach ($list as $key => $value) {
            $res= M('siji')->where(array('openid'=>$value['openid']))->field('xingming,dianhua')->find();
            $list[$key]['chufa_time']     = $value['starttime'];

            if(!empty($res))
            {
                $list[$key]['siji_name']      = $res['xingming'];
                $list[$key]['siji_dianhua']   = $res['dianhua'];
            }else
            {
                $list[$key]['siji_name']      = '';
                $list[$key]['siji_dianhua']   = '';
            }
            
            $list[$key]['status']   = $status[$value['status']];


           

            if($value['pay_statu']==1)
            {
                if($value['pay_status_sk'] ==1)
                {
                    $list[$key]['pay_statu']='现金支付';
                }else
                {
                    $list[$key]['pay_statu']='线上支付';
                }
            }else
            {
                $list[$key]['pay_statu']='未支付';
            }

           

        //手续费
        $tixianfeilv = D('user')->field('tixianfeilv,offline,offline1,offline2,offline3')->find(1);

        if($value['pay_status_sk']==0)
        {      
            $shouxubili = ($tixianfeilv['tixianfeilv']+$tixianfeilv['offline1']+$tixianfeilv['offline2']+$tixianfeilv['offline3'])/100;
            
        }else if($value['pay_status_sk'] ==1)
        {
            $shouxubili = ($tixianfeilv['offline']+$tixianfeilv['offline1']+$tixianfeilv['offline2']+$tixianfeilv['offline3'])/100;
        }
        
        // $order['tixianfeilv']  = $order['price']*($shouxubili);
        // $order['practical']    = $order['price']-($order['price']*($shouxubili));
        $list[$key]['tixianfeilv']    = $value['price']*($shouxubili);



        $list[$key]['practical']    = $value['price']-$list[$key]['tixianfeilv'];

            $list[$key]['addtime']  = date('Y-m-d H:i:s',$value['addtime']);

            unset($list[$key]['openid']);
            unset($list[$key]['pathid']); 
            unset($list[$key]['starttime']); 
            unset($list[$key]['pay_status_sk']);
            unset($list[$key]['total_price']); 
            
        }
        $headTitle = "小易出行订单数据"; 
        $title = "小易出行订单数据"; 
        $headtitle= "<tr style='height:50px;border-style:none;'>
                        <th border=\"0\" style='height:60px;width:270px;font-size:22px;' colspan='11' >
                        {$headTitle}</th>
                    </tr>"; 

        $titlename = "<tr> 
                           <th style='width:150px;'>乘客手机号</th> 
                           <th style='width:100px;'>人数</th> 
                           <th style='width:100px;'>出发地</th> 
                           <th style='width:100px;'>目的地</th> 
                           <th style='width:100px;'>支付状态</th>
                           <th style='width:200px;'>下单时间</th>
                           <th style='width:100px;'>订单状态</th>
                           <th style='width:100px;'>价格</th>

                           <th style='width:200px;'>发车时间</th>

                           <th style='width:100px;'>司机名称</th> 
                           <th style='width:100px;'>司机电话</th>
                           <th style='width:100px;'>服务费</th> 
                           <th style='width:100px;'>费用</th> 
                   </tr>"; 
                   $filename = $title.".xls"; 
        $this->excelData($list,$headtitle,$titlename,$filename); 
    }

    /* 
    *处理Excel导出 
    *@param $datas array 设置表格数据 
    *@param $titlename string 设置head 
    *@param $title string 设置表头 
    */ 
    public function excelData($datas,$titlename,$title,$filename){ 
                $str = "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\nxmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\nxmlns=\"http://www.w3.org/TR/REC-html40\">\r\n<head>\r\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\r\n</head>\r\n<body>"; 
                $str .="<table border=1><head>".$titlename."</head>"; 
                $str .= $title; 
                foreach ($datas  as $key=> $rt ) 
                { 
                    $str .= "<tr>"; 
                    foreach ( $rt as $k => $v ) 
                    { 
                        $str .= "<td>{$v}</td>"; 
                    } 
                    $str .= "</tr>\n"; 
                } 
                $str .= "</table></body></html>"; 
                header( "Content-Type: application/vnd.ms-excel; name='excel'" ); 
                header( "Content-type: application/octet-stream" ); 
                header( "Content-Disposition: attachment; filename=".$filename ); 
                header( "Cache-Control: must-revalidate, post-check=0, pre-check=0" ); 
                header( "Pragma: no-cache" ); 
                header( "Expires: 0" ); 
                exit( $str ); 
    }

    public function wheres($datas)
    {
        if (IS_POST || IS_GET) {
           if (I('wtime')) {
               $wtime = strtotime(I('wtime'));
           } else {
               $wtime = 0;
           }

           

           if (I('gntime')) {
               $ntime = strtotime(I('ntime'));
           } else {
               $ntime = time();
           }

            if (I('kehuname')) {
                $mae['name'] = array('like', '%' . I('kehuname') . '');
                $kh = M('wxuser')->where($mae)->select();
                foreach ($kh as $k => $v) {
                    $khname = $v['openid'] . ',';
                }

                $khname2 = rtrim($khname, ",");

            } else {
                $khname2 = '';
            }



            // echo $sijidianhua;
            if (I('is_px')) {
                if (I('is_px') == 1) {
                    $sor = 'addtime desc';
                } else {
                    $sor = 'starttime desc';
                }
            } else {
                $sor = 'addtime desc';
            }



            if (!empty(I('wtime2')) && !empty(I('ntime2'))) {
                $wtime2 = I('wtime2');
                $ntime2 = I('ntime2');
                $wheretime['starttime'] = array('between', '' . $wtime2 . ',' . $ntime2 . '');
            } else {
                $wtime2 = '';
                $ntime2 = date('Y-m-d H:i:s');
            }



            if (!empty(I('wtime')) && !empty(I('ntime'))) {
                $wtime = strtotime(I('wtime'));
                $ntime = strtotime(I('ntime'));
                $wheretime['addtime'] = array('between', '' . $wtime . ',' . $ntime . '');
            } else {
                $wtime = 0;
                $ntime = time();
            }
            if ($wheretime == '') {
                $wheretime['addtime'] = array('between', '' . $wtime . ',' . $ntime . '');
            }
            if (!empty(I('is_pay'))) {
                $wheretime['pay_statu'] = I('is_pay');
            }
            $this->assign('wtime', I('wtime'));
            $this->assign('ntime', I('ntime'));
            $wherex = array(
                'starttime' => array('between', '' . date('Y-m-d H:i:s', $wtime) . ',' . date('Y-m-d H:i:s', $ntime) . ''),
                'addtime' => array('between', '' . $wtime . ',' . $ntime . ''),
                '_logic' => 'or',
            );


            // echo $wtime;
            // echo '-';
            // echo $ntime;die;


            if ($khname2) {


                $where1 = array(
                    '_complex' => $wheretime,


                    // 'siji' => array('like', '%' . I('sj')),   cbing 2018年05月19日20:09:05
                    'openid' => $khname2,
                );
            } else {

                $where1 = array(
                    '_complex' => $wheretime,
                    // 'dianhua' => array('like', '%' . I('dianhua')),

                    // 'siji' => array('like', '%' . I('sj')),   cbing 2018年05月19日20:09:12
                );
            }


        } else {
            $where1 = array(
                'addtime' => array('like', '%'), 
            );
            $sor = 'id desc';
        }


            $sijixingming = urldecode(I('xingming'));
            $sijidianhua = I('dianhua');
            // echo $sijidianhua;
            // if(I('xingming')){
            //     $sijixingming = I('xingming');
            // }
            // if(I('dianhua')){
            //     $sijidianhua = I('dianhua');
            // }
            if($sijixingming){
                $where1 = array(
                    '_complex' => $wheretime,
                    'xingming' => array('like', '%'.$sijixingming.'%'), 
                );
            }

            if($sijidianhua){
                $where1 = array(
                    '_complex' => $wheretime,
                    'dianhua' => array('like', '%'.$sijidianhua.'%'), 
                );
            }

           
            // $where['pay_status_sk'] = I('pay_status_sk');
            // $where1 = array(
            //     '_complex' => $wheretime,
            //     'pay_status_sk' => array('eq',I('pay_status_sk')), 
            // );
             

        //全部订单
        // $where = array(

        //     '_complex' => $where1, // 复合查询

        // );

        $where = $where1;

        //未支付订单
        $where2 = array(
            'pay_statu' => 0,
            '_complex' => $where1, // 复合查询

        );
        //已支付订单
        $where3 = array(
            'pay_statu' => 1,
            '_complex' => $where1, // 复合查询
        );
        //已完成订单
        $where4 = array(
            'order_statu' => 6,
            '_complex' => $where1, // 复合查询

        );
        //未完成订单
        $where5 = array(
            'order_statu' => array('neq', 6),
            '_complex' => $where1, // 复合查询

        );
        $where6 = array(
            'pay_statu' => 1,
            'is_ypay' => 1,
            '_complex' => $where1, // 复合查询

        );
        
        $where['status']=I('statu');

        if($where['status']=='5')
        {
            $where['status']=array('elt',5);
        }elseif($where['status'] == 6){
            $where['status'] = array('eq',6);
        }elseif($where['status'] == 7){
            $where['status'] = array('eq',7);
        }else{
            unset($where['status']);
        }

        $pay_status_sk = I('pay_status_sk');

        if($pay_status_sk ==2){
            $where['pay_status_sk'] = 0;
            $where['status'] = 6;
        }elseif($pay_status_sk ==1){
            $where['pay_status_sk'] = $pay_status_sk;
        }



        if(I('order_cwstatus'))
        {
            unset($where['pay_statu']);
            // unset($where['_complex']);
            unset($where['dianhua']);
            $where['order_cwstatus']=I('order_cwstatus');
            $this->assign('order_cwstatus',I('order_cwstatus'));
        }
        
        if(I('open_status'))
        {
            $where['openid'] ='';
        }

        return $where;
    }


   
    /**
     * 返回唯一的号码
     */
    public function unqiueNumber(){    //'105000048165107H'.
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 6);
    }
    /**
     * 新建订单
     */
    public function addOrder()
    {
        $data   = I();
        if(IS_POST)
        {   
            empty($data['mobile'])      && $this->error('乘客手机号不能为空');
            !preg_match("/^1[123456789]{1}\d{9}$/",$data['mobile']) && $this->error('乘客手机号格式不正确');

            empty($data['openid'])     && $this->error('请选择司机');

            empty($data['path'])        && $this->error('请选择路线');
            $path   = D('price')->field('id,from_city,end_city,price,ck_city')->where('id='.$data['path'])->find();

            empty($data['chufa_time'])  && $this->error('出发时间不能为空');

            $user=D('siji')->field('id,openid,dianhua,xingming,city')->where('openid="'.$data['openid'].'" and status=1')->find();
            
            $chenke=D('siji')->field('id,openid,dianhua,xingming,city')->where('dianhua='.$data['mobile'])->find();
            empty($user) && $this->error('找不到该司机或司机未被审核通过');

            
            $result     = array(
                'orderid'       => $this->unqiueNumber(),
                'openid'        => $user['openid'],
                'start'         => $path['from_city'],
                'end'           => $path['end_city'],
                'price'         => $path['price'],
                'starttime'     => $data['chufa_time'],
                'addtime'       => time(),
                'num'           => 1,
                'pathid'        => $data['path'],
                'guding'        => $path['from_city'],
                'dianhua'       => $user['dianhua'],
                'xingming'      => $user['xingming'],
                'order_cwstatus'=> 1,
                'mobile'        => $data['mobile'],
            );
            $info = D('xllog')->add($result);
            !empty($info)?$this->success('创建成功'):$this->error('创建失败');die;
        }

        $path   = D('price')->field('id,from_city,end_city,price,ck_city')->select();
        $this->assign(array(
            'open_status'   => $data['open_status'],
            'path'          => $path,
            ));
        $this->display();
    }

    /**
     * 查询用户
     * @return [type] [description]
     */
    public function selectname()
    {
        $data   = I();
        empty($data['name']) && datamsg(0,"请填写司机姓名或者手机号");

        $map['dianhua|xingming']     = array(array('like','%'.$data['name'].'%'),array('like','%'.$data['name'].'%'),'_multi'=>true);
        $map['status']               = 1;

        $result = D('siji')->field('id,xingming,dianhua,openid')->where($map)->select();
       
        empty($result) && datamsg(0,"没有找到该司机或还未审核通过");

        datamsg(1,"成功",$result);

    }

}
